package com.example.normal.controller;

import com.example.base.result.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    /**
     * 文件下载，文件的路径在resources/files/下
     * @author wanghongyu02
     * @date 2024-07-25 9:51
     * @param filename
     * @return org.springframework.http.ResponseEntity<org.springframework.core.io.Resource>
     */
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam String filename) {
        try {
            Resource resource = new ClassPathResource("files/" + filename);
            log.info("文件路径: " + resource);

            if (!resource.exists() || !resource.isReadable()) {
                log.info("文件不存在或不可读！");
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }

            Path filePath = resource.getFile().toPath();

            String contentType = Files.probeContentType(filePath);
            if (contentType == null) {
                contentType = "application/octet-stream";
            }

            return ResponseEntity.ok()
                    .contentType(org.springframework.http.MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);

        } catch (Exception e) {
            log.error("下载文件失败！", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 文件上传，文件保存在项目同级目录的uploads文件夹下（呦西，其实控制台会print）
     * @author wanghongyu02
     * @date 2024-07-25 10:00
     * @param file
     * @return org.springframework.http.ResponseEntity<java.lang.String>
     */
    @PostMapping("/upload")
    public AjaxResult handleFileUpload(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return AjaxResult.error("文件为空");
        }

        try {
            // 获取当前工作目录
            String uploadDir = System.getProperty("user.dir") + File.separator + "uploads";
            log.info("文件计划上传目录: " + uploadDir);

            // 创建上传目录（如果不存在的话）
            File uploadDirFile = new File(uploadDir);
            if (!uploadDirFile.exists()) {
                uploadDirFile.mkdirs();
            }

            // 获取上传的文件名
            String fileName = file.getOriginalFilename();

            // 目标文件
            File destinationFile = null;
            if (fileName != null) {
                destinationFile = new File(uploadDirFile, fileName);
            }

            // 将文件保存到目标路径
            if (destinationFile != null) {
                file.transferTo(destinationFile);
            }

            return AjaxResult.success("文件上传成功");

        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("文件上传失败");
        }
    }
}
